﻿using System.Linq;
using Contracts.Entities;

namespace Model.MovieElements
{
    public class WriteGenres : WriteMovieElement
    {
        public WriteGenres(MovieDatabaseEntities entities, Movies movie)
            : base(entities, movie)
        {
        }

        public override void Insert(MovieElement element)
        {
            var entity = entities.Genres.SingleOrDefault(m => m.Name == element.Name);
            if (entity == null)
            {
                entity = GenreConverter.GetEntity(element);
                entity.Id = GetLastID() + 1;
            }

            movie.Genres.Add(entity);
            entities.SaveChanges();
        }

        public override void Delete(MovieElement element)
        {
            var genre = movie.Genres.SingleOrDefault(m => m.Id == element.Id);

            if (genre == null)
                return;

            movie.Genres.Attach(genre);
            movie.Genres.Remove(genre);
            entities.SaveChanges();
        }

        private int GetLastID()
        {
            var genre = entities.Genres.OrderByDescending(m => m.Id).FirstOrDefault();
            return genre != null ? genre.Id : 0;
        }

        public override MovieElementType GetMovieElementType()
        {
            return MovieElementType.Genre;
        }
    }
}
